# coding: utf-8

import config
import app.tools as tool
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import SIGNAL
from app.tools.dialog import MessageBox
from app.ui.icon import Icon
from app.ui.tab.tab_page_abstract import TabPageAbstract
from app.tools.table import TableWidget, TableWidgetItem


class TabPageHash(TabPageAbstract):

    def __init__(self, tab, item, factory, name):
        super(TabPageHash, self).__init__(tab, item, factory, name)
        self.parent = super(TabPageHash, self)
        self.icon = Icon()
        self.tab_widget_page_hash = self.parent.get_instance()

        self.two_horizontal_layout = QtGui.QHBoxLayout()
        self.two_horizontal_layout.setObjectName(tool._from_utf8("two_horizontal_layout"))

        self.hash_table = TableWidget(self.tab_widget_page)
        self.hash_table.set_object_name('hash_table')
        self.hash_table.init_ui()
        self.hash_table.set_column_count(2)
        # self.hash_table.setLineWidth(5)
        # self.hash_table.setMidLineWidth(5)
        # 单选
        self.hash_table.set_selection_mode(TableWidget.SingleSelection)
        # 设置选择行为时每次选择一行
        self.hash_table.set_selection_behavior(TableWidget.SelectRows)
        # 设置不可编辑
        self.hash_table.set_edit_triggers(TableWidget.NoEditTriggers)
        self.hash_table.set_horizontal_header(0, 'Key', self.icon.get(config.ICON_KEY))
        self.hash_table.set_horizontal_header(1, 'Value', self.icon.get(config.ICON_LOG))

        # __sorting_enabled = self.hash_table.isSortingEnabled()
        # self.hash_table.setSortingEnabled(__sorting_enabled)
        self.hash_table.connect(self.hash_table, SIGNAL('cellClicked(int, int)'), self.event_table_row_clicked)
        self.two_horizontal_layout.addWidget(self.hash_table)

        self.two_vertical_layout = QtGui.QVBoxLayout()
        self.two_vertical_layout.setObjectName(tool._from_utf8("two_vertical_Layout"))

        self.hash_add_row_button = QtGui.QPushButton(self.tab_widget_page)
        self.hash_add_row_button.setIcon(self.icon.get(config.ICON_ADD))
        self.hash_add_row_button.setObjectName(tool._from_utf8("hash_add_row_button"))
        self.hash_add_row_button.setText(tool._from_utf8('Add Row'))
        self.hash_add_row_button.clicked.connect(self.event_table_add_row)
        self.two_vertical_layout.addWidget(self.hash_add_row_button)

        self.hash_delete_row_button = QtGui.QPushButton(self.tab_widget_page)
        # self.hash_delete_row_button.setGeometry(QtCore.QRect(560, 90, 131, 30))
        self.hash_delete_row_button.setIcon(self.icon.get(config.ICON_DEL))
        self.hash_delete_row_button.setObjectName(tool._from_utf8("hash_delete_row_button"))
        self.hash_delete_row_button.setText(tool._from_utf8('Delete Row'))
        self.hash_delete_row_button.clicked.connect(self.event_table_delete_row)
        self.two_vertical_layout.addWidget(self.hash_delete_row_button)

        self.hash_reload_value_button = QtGui.QPushButton(self.tab_widget_page)
        self.hash_reload_value_button.setIcon(self.icon.get(config.ICON_REFRESH))
        self.hash_reload_value_button.setObjectName(tool._from_utf8("hash_reload_value_button"))
        self.hash_reload_value_button.setText(tool._from_utf8('Reload Value'))
        self.hash_reload_value_button.clicked.connect(self.event_table_reload)
        self.two_vertical_layout.addWidget(self.hash_reload_value_button)
        spacer_item = QtGui.QSpacerItem(20, 20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.two_vertical_layout.addItem(spacer_item)
        self.two_horizontal_layout.addLayout(self.two_vertical_layout)

        self.parent.add_layout(self.two_horizontal_layout)

        self.three_vertical_layout = QtGui.QVBoxLayout()
        self.three_vertical_layout.setObjectName(tool._from_utf8("three_vertical_layout"))
        self.three_horizontal_layout = QtGui.QHBoxLayout()
        self.three_horizontal_layout.setObjectName(tool._from_utf8("three_horizontal_layout"))

        self.hash_key_label = QtGui.QLabel(self.tab_widget_page)
        # self.hash_key_label.setGeometry(QtCore.QRect(10, 260, 41, 18))
        self.hash_key_label.setObjectName(tool._from_utf8("hash_label"))
        self.hash_key_label.setText(tool._from_utf8('Key:'))
        self.three_horizontal_layout.addWidget(self.hash_key_label)

        self.hash_key_text = QtGui.QLineEdit(self.tab_widget_page)
        # self.hash_key_text.setEnabled(False)
        # self.hash_key_text.setGeometry(QtCore.QRect(50, 250, 641, 31))
        self.hash_key_text.setObjectName(tool._from_utf8("hash_key_text"))
        self.three_horizontal_layout.addWidget(self.hash_key_text)
        self.three_vertical_layout.addLayout(self.three_horizontal_layout)
        self.parent.add_layout(self.three_vertical_layout)

        self.four_vertical_layout = QtGui.QVBoxLayout()
        self.four_vertical_layout.setObjectName(tool._from_utf8("four_vertical_layout"))
        self.four_horizontal_layout = QtGui.QHBoxLayout()
        self.four_horizontal_layout.setObjectName(tool._from_utf8("four_horizontal_layout"))

        self.hash_value_label = QtGui.QLabel(self.tab_widget_page)
        # self.hash_value_label.setGeometry(QtCore.QRect(10, 300, 51, 18))
        self.hash_value_label.setObjectName(tool._from_utf8("hash_value_label"))
        self.hash_value_label.setText(tool._from_utf8('Value:'))
        self.four_horizontal_layout.addWidget(self.hash_value_label)

        spacer_item = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
        self.four_horizontal_layout.addItem(spacer_item)


        self.hash_value_format_label = QtGui.QLabel(self.tab_widget_page)
        # self.value_format_label.setGeometry(QtCore.QRect(450, 300, 101, 18))
        self.hash_value_format_label.setObjectName(tool._from_utf8("value_format_label"))
        self.hash_value_format_label.setText(tool._from_utf8('View value as:'))
        self.four_horizontal_layout.addWidget(self.hash_value_format_label)

        self.hash_value_format_select = self.parent.get_combo_box(self.tab_widget_page)
        self.four_horizontal_layout.addWidget(self.hash_value_format_select)

        # self.hash_save_row_button = QtGui.QPushButton(self.vertical_box_widget)
        # self.hash_save_row_button.setIcon(self.icon.get(config.ICON_SAVE))
        # self.hash_save_row_button.setObjectName(tool._from_utf8("hash_save_row_button"))
        # self.hash_save_row_button.setText(tool._translate("MainWindow", "OK", None))
        # self.hash_save_row_button.clicked.connect(self.event_table_save_row)
        # self.four_horizontal_layout.addWidget(self.hash_save_row_button)

        self.four_vertical_layout.addLayout(self.four_horizontal_layout)

        self.hash_value_text = QtGui.QTextEdit(self.tab_widget_page)
        # self.hash_value_text.setGeometry(QtCore.QRect(10, 330, 681, 181))
        # self.hash_value_text.setStyleSheet(tool._from_utf8("border-color: rgb(150, 150, 150);background-color: rgb(255, 255, 255);"))
        self.hash_value_text.setObjectName(tool._from_utf8("hash_value_text"))
        self.four_vertical_layout.addWidget(self.hash_value_text)
        self.parent.add_layout(self.four_vertical_layout)
        self.parent.set_stretch(0, 1)
        self.parent.set_stretch(1, 3)
        self.parent.set_stretch(2, 1)
        self.parent.set_stretch(3, 1)
        self.parent.set_stretch(3, 4)
        self.event_table_reload()

    def event_table_row_clicked(self, row, _):
        hash_key_item = self.hash_table.item(row, 0)
        if hash_key_item:
            hash_key = hash_key_item.text()
            self.hash_key_text.setText(hash_key)
        else:
            self.hash_key_text.setText('')
        hash_value_item = self.hash_table.item(row, 1)
        if hash_value_item:
            hash_value = hash_value_item.text()
            self.hash_value_text.setText(hash_value)
        else:
            self.hash_value_text.setText('')

    def event_table_add_row(self):
        row_count = self.hash_table.row_count()
        last_count = row_count - 1
        last_hash_key_item = self.hash_table.item(last_count, 0)
        last_hash_value_item = self.hash_table.item(last_count, 1)
        if not last_hash_key_item or not last_hash_value_item:
            return
        if not last_hash_key_item.text() or not last_hash_value_item.text():
            return
        self.hash_table.insert_row(row_count)
        item_key = self.hash_table.set_item(row_count, 0, '')
        item_value = self.hash_table.set_item(row_count, 1, '')
        self.hash_table.setCurrentItem(item_key)
        self.hash_table.selectRow(row_count)
        self.event_table_row_clicked(row_count, 0)
        self.hash_table.vertical_scroll_bar().setValue(row_count)
        # print(dir(self.hash_table.verticalScrollBar()))
        # print(self.hash_table.verticalScrollBar().value())
        # print(self.hash_table.verticalScrollBar().scroll())

    def event_table_delete_row(self):
        row = self.hash_table.current_row()
        if row > -1:
            # item_key = self.hash_table.item(row, 0)
            # key = item_key.text()
            # self.factory.hdel(self.name, key)
            self.hash_table.remove_row(row)

    def event_table_reload(self):
        hash_value = self.factory.hall(self.name)
        if not hash_value:
            return
        hash_keys = hash_value.keys()
        self.hash_table.set_row_count(len(hash_keys))
        for (i, hash_key) in enumerate(hash_keys):
            self.hash_table.set_item(i, 0, hash_key)
            self.hash_table.set_item(i, 1, hash_value.get(hash_key))
        self.hash_table.select_row(0)
        self.event_table_row_clicked(0, 0)

    def event_table_save_row(self):
        print('event_table_save_row')
        current_row = self.hash_table.currentRow()
        new_hash_key = self.hash_key_text.text()
        if not new_hash_key:
            MessageBox.info('tips', 'hash key not null!')
            return
        item_key = self.hash_table.item(current_row, 0)
        old_hash_key = item_key.text()
        if old_hash_key != new_hash_key:
            self.factory.hdel(self.name, old_hash_key)
        item_key.setText(new_hash_key)
        hash_value = self.hash_value_text.toPlainText()
        item_value = self.hash_table.item(current_row, 1)
        item_value.setText(hash_value)

    def event_save_clicked(self):
        self.event_table_save_row()
        value_dict = dict()
        row_count = self.hash_table.rowCount()
        for i in range(row_count):
            item_key = self.hash_table.item(i, 0)
            item_value = self.hash_table.item(i, 1)
            if not item_key or not item_value:
                continue
            key = item_key.text()
            if not key or key.isEmpty() or key.isNull():
                continue
            key = tool.qstring_to_string(key)
            value = item_value.text()
            value = tool.qstring_to_string(value)
            value_dict[key] = value
        print(value_dict)
        self.factory.hmset(self.name, value_dict)
        MessageBox.info('tips', 'save success!')

    def event_format_changed(self, index):
        print('event_format_changed')
        print(index)